--name=value;Expires=;Max-Age=;path=;domain=;httponly;secure
local STRING_LOWER = string.lower
local STRING_FIND = string.find
local STRING_GSUB = string.gsub
local STRING_SUB = string.sub
local TABLE_CONCAT = table.concat
local cookies = {}
local http_cookie = {}

local function trim(s)
    return (STRING_GSUB(s, "^%s*(.-)%s*$", "%1")) 
end

local function save_cookie(tt)
    local domain = cookies[tt.domain]
    if domain == nil then
        domain = {}
        domain[tt.name] = tt
        cookies[tt.domain] = domain
    else
        domain[tt.name] = tt
    end
end

local function parse_cookie(tt, data)
    if STRING_SUB(data, 1, 8) == "Expires=" then
    elseif STRING_LOWER(STRING_SUB(data, 1, 8)) == "max-age=" then
    elseif STRING_LOWER(STRING_SUB(data, 1, 5)) == "path=" then
        tt.path = STRING_SUB(data, 6)
    elseif STRING_LOWER(STRING_SUB(data, 1, 7)) == "domain=" then
        tt.domain = STRING_SUB(data, 8)
    elseif STRING_LOWER(STRING_SUB(data, 1, 8)) == "httponly" then
        tt.httponly = true
    elseif STRING_LOWER(STRING_SUB(data, 1, 6)) == "secure" then
        tt.secure = true
    end
end

function http_cookie.set_cookie(cookie)
    local tt = {}
    local spos = 1
    local epos = STRING_FIND(cookie, "=", spos)
    if epos == nil then return end
    tt.name = STRING_SUB(cookie, spos, epos - 1)
    spos = epos + 1
    epos = STRING_FIND(cookie, ";", spos)
    if epos == nil then return end
    tt.value = STRING_SUB(cookie, spos, epos -1)
    spos = epos + 1
    local data
    while true do
        epos = STRING_FIND(cookie, ";", spos)
        if epos == nil then
            data = trim(STRING_SUB(cookie, spos))
            parse_cookie(tt, data)
            break
        else
            data = trim(STRING_SUB(cookie, spos, epos -1))
            parse_cookie(tt, data)
            spos = epos + 1
        end
    end
    save_cookie(tt)
end

function http_cookie.get_cookie(req)
    local host = req.host
    if STRING_SUB(host, 1, 3) == "www" then
        host = STRING_SUB(host, 4)
    end
    local items = {}
    local i = 1

    for domain_k, domain in pairs(cookies) do
        local domain_klen = #domain_k
        if STRING_SUB(host, #host - domain_klen +1) == domain_k then
            for k,v in pairs(domain) do
                items[i] = k.."="..v.value
            end
        end
    end
    local value = TABLE_CONCAT(items, ";")
    return value
end

return http_cookie